package xin.marcher.redisson.demo;

import org.redisson.Redisson;
import org.redisson.RedissonMultiLock;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

public class RedissonDemo {

    public static void main(String[] args) {
        Config config = new Config();
        config.useClusterServers()
                .addNodeAddress("redis://49.232.197.51:7001")
                .addNodeAddress("redis://49.232.197.35:7003")
                .addNodeAddress("redis://49.232.197.35:7001")
                .addNodeAddress("redis://49.232.197.51:7003")
                .addNodeAddress("redis://49.232.197.35:7002")
                .addNodeAddress("redis://49.232.197.51:7002")
                ;

        RedissonClient redisson = Redisson.create(config);

        // 可重入锁
        RLock lock = redisson.getLock("anyLock");
        lock.lock(10000, TimeUnit.MILLISECONDS);

       try {
           Thread.sleep(10000);
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
          lock.unlock();
       }

        // 公平锁
//       RLock fairLock = redisson.getFairLock("anyLock");
//       fairLock.lock();
//
//       fairLock.unlock();

        // 联锁
//        RLock lock1 = redisson.getLock("lock1");
//        RLock lock2 = redisson.getLock("lock2");
//        RLock lock3 = redisson.getLock("lock3");
//
//        RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
//        // 同时加锁：lock1 lock2 lock3
//        // 所有的锁都上锁成功才算成功。
//        lock.lock();
//        lock.unlock();

        // 红锁
//        RLock lock1 = redisson.getLock("lock1");
//        RLock lock2 = redisson.getLock("lock2");
//        RLock lock3 = redisson.getLock("lock3");
//
//        RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
//        // 同时加锁：lock1 lock2 lock3
//        // 所有的锁都上锁成功才算成功。
//        lock.lock();
//        lock.unlock();


        // 读写锁
//        RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock");
//        // 最常见的使用方法
//        rwlock.readLock().lock();
//        // 或
//        rwlock.writeLock().lock();
    }
}
